﻿/*
 * Imigrasi SMS (Special built for Immigration Office)
 * Copyright (C) 2010 Wish Enterprise Development Team

 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 * 
 * Contact Us:
 * Author   : Khoirul Imamudin
 * E-Mail   : contact@wishenterprise.com     Website: http://www.wishenterprise.com
 * 
 * */

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using SmsEntity;
using SmsEntity.Local;
using SmsRepository;
using SmsRepository.Local;

namespace SmsManualRespond
{

    /// <summary>
    /// MainPanel
    /// </summary>
    public partial class MainPanel : Form
    {
        private readonly ListViewColumnSorter _lvwColumnSorter;

        private User _user;

        /// <summary>
        /// Initializes a new instance of the <see cref="MainPanel"/> class.
        /// </summary>
        public MainPanel()
        {
            InitializeComponent();

            _lvwColumnSorter = new ListViewColumnSorter();
            lsvData.ListViewItemSorter = _lvwColumnSorter;

            cboRepliedStatus.SelectedIndex = 0;
        }

        private void BtnExitClick(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private static void SetAlternateColor(ListView obj)
        {
            for (int index = 0; index < obj.Items.Count; index++)
            {
                ListViewItem r = obj.Items[index];
                r.BackColor = (index%2).Equals(0) ? Color.Cornsilk : Color.White;
            }
        }

        private void LsvDataColumnClick(object sender, ColumnClickEventArgs e)
        {
            if (e.Column == _lvwColumnSorter.SortColumn)
            {
                _lvwColumnSorter.Order = _lvwColumnSorter.Order == SortOrder.Ascending
                                             ? SortOrder.Descending
                                             : SortOrder.Ascending;
            }
            else
            {
                _lvwColumnSorter.SortColumn = e.Column;
                _lvwColumnSorter.Order = SortOrder.Ascending;
            }

            lsvData.Sort();
        }

        private void RemoveSelectedFromDatabaseToolStripMenuItemClick(object sender, EventArgs e)
        {
            var db = new InboxNonServiceBase();

            foreach (ListViewItem lv in lsvData.SelectedItems)
                db.Delete(new InboxNonService {ID = int.Parse(lv.Name)});

            BtnSearchClick(this, null);
        }

        private void LsvDataItemActivate(object sender, EventArgs e)
        {
            txtID.Text = lsvData.SelectedItems[0].Name.Trim();
            txtSenderNumber.Text = lsvData.SelectedItems[0].Text.Trim();
            txtMessage.Text = lsvData.SelectedItems[0].SubItems[1].Text.Trim();
            txtSendingDateTime.Text = lsvData.SelectedItems[0].SubItems[2].Text.Trim();
        }

        private void BtnSendClick(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtSenderNumber.Text.Trim())) return;
            if (string.IsNullOrEmpty(txtMessage.Text.Trim())) return;
            if (string.IsNullOrEmpty(txtReply.Text.Trim())) return;

            var obj = new Outbox
                          {
                              DestinationNumber = txtSenderNumber.Text.Trim(),
                              TextDecoded = txtReply.Text.Trim()
                          };

            var dboutbox = new OutboxBase();

            if (dboutbox.Save(obj) == 1)
            {
                var dbns = new InboxNonServiceBase();

                dbns.UpdateRepliedStatus(int.Parse(txtID.Text.Trim()), true);

                var dbreply = new ReplyNonServiceBase();

                dbreply.Save(new ReplyNonService
                                 {
                                     ID = int.Parse(txtID.Text.Trim()),
                                     Message = txtReply.Text.Trim()
                                 });

                ClearForm();
            }
        }

        /// <summary>
        /// Clears the form.
        /// </summary>
        private void ClearForm()
        {
            txtSenderNumber.Clear();
            txtMessage.Clear();
            txtSendingDateTime.Clear();
            txtReply.Clear();
        }

        private void ReplyToolStripMenuItemClick(object sender, EventArgs e)
        {
            LsvDataItemActivate(this, null);
        }

        private void AboutMeToolStripMenuItemClick(object sender, EventArgs e)
        {
            MessageBox.Show(@"Copyleft (C) 2010 Wish Enterprise",
                            @"Imigrasi SMS Manual Respond v2.0",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void BtnClearClick(object sender, EventArgs e)
        {
            ClearForm();
        }

        private void BtnSearchClick(object sender, EventArgs e)
        {
            var db = new InboxNonServiceBase();
            List<InboxNonService> rs = db.GetAllByRepliedStatus(cboRepliedStatus.SelectedIndex == 1);
            lsvData.Items.Clear();

            foreach (InboxNonService r in rs)
            {
                ListViewItem lv = lsvData.Items.Add(r.ID.ToString(), r.SenderNumber, 0);

                lv.SubItems.Add(r.Message);
                lv.SubItems.Add(r.ReceivingDateTime.ToString("yyyy-MM-dd HH:mm:ss"));
            }

            SetAlternateColor(lsvData);
            stbResult.Text = string.Format("Result: {0} record(s)", lsvData.Items.Count);
        }

        private void CboRepliedStatusSelectedIndexChanged(object sender, EventArgs e)
        {
            splDasar.Panel2Collapsed = cboRepliedStatus.SelectedIndex == 0;
        }

        private void LsvDataClick(object sender, EventArgs e)
        {
            if (lsvData.SelectedItems.Count <= 0) return;

            lsvReply.Items.Clear();
            List<ReplyNonService> replies =
                new ReplyNonServiceBase().GetAllById(int.Parse(lsvData.SelectedItems[0].Name.Trim()));

            foreach (ReplyNonService r in replies)
                lsvReply.Items.Add(r.ID.ToString(), r.Message, 1);

            SetAlternateColor(lsvReply);
        }

        private void MnuDbcClick(object sender, EventArgs e)
        {
            using (var f = new DBLogonUI())
                f.ShowDialog(this);
        }

        private void MnuWorkflowClick(object sender, EventArgs e)
        {
            using (var f = new WorkflowUI())
            {
                f.ShowDialog(this);
            }
        }

        private void MainPanel_Shown(object sender, EventArgs e)
        {
            if (!AuthenticateUser(this))
            {
                Close();
                Dispose();
                Application.Exit();
            }
        }

        public bool AuthenticateUser(IWin32Window parent)
        {
            DialogResult dlg;
            using (var f = new LogonPresentation())
            {
                dlg = f.ShowDialog(parent);
                _user = f.User;
            }

            if (dlg == DialogResult.OK)
            {
                
            }

            return (dlg.Equals(DialogResult.OK));
        }

        private void btnLogoff_Click(object sender, EventArgs e)
        {
            Application.Restart();
        }

        private void btnChangePassword_Click(object sender, EventArgs e)
        {
            using (var f = new PasswordUI(_user))
            {
                f.ShowDialog(this);
            }
        }

        /// <summary>
        /// Handles the TextChanged event of the txtID control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void txtID_TextChanged(object sender, EventArgs e)
        {
            ((TextBox)sender).Text = EnvironmentRepository.SuppressChar(((TextBox)sender).Text);
        }

        /// <summary>
        /// Handles the TextChanged event of the txtReply control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void txtReply_TextChanged(object sender, EventArgs e)
        {
            ((TextBox)sender).Text = EnvironmentRepository.SuppressChar(((TextBox)sender).Text);
        }
    }
}